package com.tansty.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.tansty.dao.mapper.*;
import com.tansty.pojo.dto.PermissionInputDTO;
import com.tansty.pojo.po.*;
import com.tansty.service.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Tansty
 * @since 2021-07-31
 */

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    RolePermissionMapper rolePermissionMapper;

    @Override
    public int updateOnePerm(PermissionInputDTO permissionInputDTO) {
        // 修改用户名
        User user = new User();
        user.setId(permissionInputDTO.getId());
        user.setUserName(permissionInputDTO.getUserName());
        userMapper.updateById(user);
        // 找到用户的role_id
        UserRole userRole = userRoleMapper.selectOne(new QueryWrapper<UserRole>().eq("user_id",permissionInputDTO.getId()));
        // 修改用户的role属性
        Role role = new Role();
        role.setId(userRole.getRoleId());
        role.setRoleName(permissionInputDTO.getRoleName());
        role.setRoleDesc(permissionInputDTO.getRoleDesc());
        roleMapper.updateById(role);
        // 修改权限对应的表
        // 先删除这个人的所有的权限，再去插入
        rolePermissionMapper.delete(new QueryWrapper<RolePermission>().eq("role_id",role.getId()));
        for (String[] perm : permissionInputDTO.getPerms()) {
            Permission permOne = permissionMapper.selectOne(new QueryWrapper<Permission>().eq("perm_tag", perm[0]));
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(role.getId());
            rolePermission.setPermId(permOne.getId());
            System.out.println(rolePermission);
            rolePermissionMapper.insert(rolePermission);
        }
        return 0;
    }

}
